package RequestHandler;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import Request.*;
import Container.*;
import DBControl.*;

public class Worker extends Thread {
    final static int err = -1;
    final static int logout = -1;
    final static int ok = 0;
    private boolean idle = true;
    private boolean quit = false;
    private SessionList sessionList;
    private DBInterface dbi;
    private Request request = null;
    private int wid;
    
    public Worker(SessionList sessionList, DBInterface dbi, int id) {
        this.sessionList = sessionList;
        this.dbi = dbi;
        wid = id;
    }
    
    public void run() {
        while (!quit) {
            try {
                if (request == null) {
                    //System.out.println("idling");
                    sleep(500);
                }
                else {
                    dbi.checkCompletion();
                    switch (request.getRequestType()) {
                        case LOGIN: 
                            login();
                            break;
                        case LOGOUT:
                            logout();
                            break;
                        case REGISTER:
                            register();
                            break;
                        case SELL:
                            sell();
                            break;
                        case BID: 
                            bid();
                            break;
                        case BUYOUT:
                            buyout();
                            break;
                        case SEARCH:
                            search();
                            break;
                        case SEARCHPAGE:
                            searchPage();
                            break;
                        case GETCATEGORY:
                            getCategory();
                            break;
                        case COMMENT:
                            comment();
                            break;
                        case VIEWDETAIL:
                            viewDetail();
                            break;
                        case VIEWCENTRE:
                            viewCentre();
                            break;
                        default:
                    }
                    request = null;
                    idle = true;
                }
            }
            catch (Exception e) {
                // TODO Auto-generated method stub 
            }
        }
    }
    
    private void getCategory() {
        try {
            if (sessionList.sessionExists(request.getUid(), request.getSid())) {
                HashMap<String, Integer> category = dbi.getCategory();
                for (Map.Entry<String, Integer> entry : category.entrySet()) {
                    System.out.println(entry.getKey() + " " + entry.getValue());
                }
                request.setSession(request.getUid(), request.getSid());
                request.setAttribute("category", category);
                request.reply();
            }
            else {
                System.out.println("Invalid Session");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void searchPage() {
        if (sessionList.sessionExists(request.getUid(), request.getSid())) {
            ArrayList<Item> items = sessionList.getSearchResult(request.getSid(), ((SearchPageRequest)request).getPage());
            request.setSession(request.getUid(), request.getSid());
            request.setAttribute("items", items);
            request.setAttribute("numPage", sessionList.getNumPage(request.getSid()));
            request.setAttribute("numResult", sessionList.getNumReseult(request.getSid()));
            request.setNextPage(request.page_searchresult);
            request.reply();
        }
        else {
            System.out.println("Invalid Session");
        }
    }

    private void viewCentre() {
        try {
            if (sessionList.sessionExists(request.getUid(), request.getSid())) {
                Center center = dbi.viewCenter(request.getUid());
                request.setSession(request.getUid(), request.getSid());
                request.setAttribute("center", center);
                request.setNextPage(request.page_pcenter);
                request.reply();
            }
            else {
                System.out.println("Invalid Session");
            }
        } catch (Exception e) {    
            e.printStackTrace();
        }
    }

    private void viewDetail() {
        try {
            if (sessionList.sessionExists(request.getUid(), request.getSid())) {
                Item item = dbi.viewDetail(((ViewDetailRequest)request).getIid());
                request.setSession(request.getUid(), request.getSid());
                request.setAttribute("item", item);
                request.setNextPage(request.page_itemdetail);
                request.reply();
            }
            else {
                System.out.println("Invalid Session");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    private void comment() {
        try {
            if (sessionList.sessionExists(request.getUid(), request.getSid())) {
                dbi.comment(request.getUid(), ((CommentRequest)request).getIid(), ((CommentRequest)request).getComment());
                Item item = dbi.viewDetail(((CommentRequest)request).getIid());
                request.setSession(request.getUid(), request.getSid());
                request.setAttribute("item", item);
                request.setNextPage(request.page_itemdetail);
                request.reply();
            }
            else {
                System.out.println("Invalid Session");
            }
        }
        catch (Exception e) {
            
        }
    }

    private void search() {
        try {
            if (sessionList.sessionExists(request.getUid(), request.getSid())) {
                ArrayList<Item> searchResult = dbi.search(((SearchRequest)request).getCriteria());
                sessionList.addSearchResult(request.getSid(), searchResult);
                ArrayList<Item> items = sessionList.getSearchResult(request.getSid(), 1);
                request.setSession(request.getUid(), request.getSid());
                request.setAttribute("items", items);
                request.setAttribute("numPage", sessionList.getNumPage(request.getSid()));
                request.setAttribute("numResult", sessionList.getNumReseult(request.getSid()));
                request.setNextPage(request.page_searchresult);
                request.reply();
            }
            else {
                System.out.println("Invalid Session");
            }
        }
        catch (Exception e) {
            
        }
        
    }

    private void buyout() {
        try {
            if (sessionList.sessionExists(request.getUid(), request.getSid())) {
                int ret = dbi.buyout(request.getUid(), ((BuyoutRequest)request).getIid());
                request.setSession(request.getUid(), request.getSid());
                request.setAttribute("status", ret);
                request.setNextPage(request.page_index);
                request.reply();
            }
            else
            {
                System.out.println("Invalid Session");
            }
        }
        catch (Exception e) {
            
        }
    }

    private void bid() {
        try {
            if (sessionList.sessionExists(request.getUid(), request.getSid())) {
                int ret = dbi.bidItem(request.getUid(), ((BidRequest)request).getIid(), ((BidRequest)request).getPrice());
                Item item = dbi.viewDetail(((BidRequest)request).getIid());
                request.setSession(request.getUid(), request.getSid());
                request.setAttribute("status", ret);
                request.setAttribute("item", item);
                request.setNextPage(request.page_itemdetail);
                request.reply();                
            }
            else {
                System.out.println("Invalid Session");
            }
        }
        catch (Exception e) {
            
        }   
    }

    private void sell() {
        try {
            if (sessionList.sessionExists(request.getUid(), request.getSid())) {
                dbi.addItem(((SellRequest)request).getItem());
                request.setSession(request.getUid(), request.getSid());
                request.setNextPage(request.page_selluploadresult);
                request.reply();
            }
            else {
                System.out.println("Invalid Session");
            }
        }
        catch (Exception e) {
            
        }   
    }

    private void register() {
        //System.out.println(wid + " enter register");
        try {
            int uid = dbi.register(((RegisterRequest)request).getUser(), ((RegisterRequest)request).getUserInfo());
            if (uid > -1) {
                Login login = dbi.login(((RegisterRequest)request).getUser());
                int sid = sessionList.addSession(uid);
                request.setSessionAttribute("name", login.getName());
                request.setSession(uid, sid);
                request.setNextPage(request.page_index);
            }
            else {
                request.setSession(err, err);
                request.setNextPage(request.page_reregister);
            }
            request.reply();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        //System.out.println(wid + " exit register");
    }

    private void logout() {
        if (sessionList.sessionExists(request.getUid(), request.getSid())) {
            sessionList.removeSearchResult(request.getSid());
            sessionList.deleteSession(request.getSid());
        }
        else {
            System.out.println("Invalid Session");
        }
        request.setNextPage(request.page_index);
        request.setSession(logout, logout);
        request.reply();
    }

    private void login() {
        try {
            Login login = dbi.login(((LoginRequest)request).getUser());
            if (login.getUid() > -1) {
                int sid = sessionList.addSession(login.getUid()); 
                request.setSessionAttribute("name", login.getName());
                request.setSession(login.getUid(), sid);
                request.setNextPage(request.page_index);
            }
            else {
                request.setSession(err, err);
                request.setNextPage(request.page_relogin);
            }
            request.reply();
        }
        catch (Exception e) {
            
        }     
    }

    public void setOccupied() {
        idle = false;
    }
    
    public boolean isIdle() {
        return idle;
    }
    
    public void quit() {
        quit = true;
    }

    public void action(Request request) {
        this.request = request;
    }
}